<?php

namespace app\admin\controller\newhouse;

use app\common\controller\Backend;

/**
 * 新房视频管理
 *
 * @icon fa fa-circle-o
 */
class NewhouseVideo extends Backend
{

    /**
     * NewhouseVideo模型对象
     * @var \app\common\model\newhouse\NewhouseVideo
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\newhouse\NewhouseVideo;
        $this->view->assign("foviList", $this->model->getFoviList());
        $this->view->assign("lxList", $this->model->getLxList());
        $this->view->assign("goodList", $this->model->getGoodList());
        $this->view->assign("flagList", $this->model->getFlagList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['category'])
                    ->where($where)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['category'])
                    ->where($where)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();

            foreach ($list as $row) {
                $row->visible(['id','title','newhouse_id','category_id','pic','url','flag','describe','updatetime']);
                $row->visible(['category']);
				$row->getRelation('category')->visible(['name']);
            }
            $list = collection($list)->toArray();
            // 能获取到newhouse 数据的时候打开
            // $list = addtion($list, 'newhouse_id');
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $count = $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            // 根据id查询 只查field限制的字段
            $list = $this->model->where($pk, 'in', $ids)->field($pk . ',pic')->select();
            $count = 0;
            foreach ($list as $k => $v) {
                // 删除单张封面 保存机制需要了解一轮，同图片上传是不是只保存一张，那这要是执行删除，其他的是不是就没有图片存在了
                $this->delImageAction($v['pic']);

                $count += $v->delete($v[$pk]);
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

    /**
     * 删除封面
     */
    public function delCover()
    {
        if ($this->request->isPost()) {
            $id = $this->request->post("id");
            $path = $this->request->post("path");
            // 觉得这段意义不大， 如果用户把图片删了，但是不保存呢
            // 这里应该想一个更好的机制来替换
            if ($id) {
                $this->model->save(['pic' => ''], ['id' => $id]);
            }

            // 执行封面删除
            $this->delImageAction($path);

            $this->success();
        }
    }

    /**
     * 删除image动作
     * @param string $path NULL
     * @return
     */
    protected function delImageAction($path = '')
    {
        // 先做单删除文件代码
        // $attachmentFile = ROOT_PATH . '/public/uploads' . $path; // 正式测试开这段
        // 测试删除代码
        $attachmentFile = ROOT_PATH . '/public' . $path;
        if (is_file($attachmentFile))
        {
            // 这里不取返回值， 看看吧。还不是很了解整个删除的流程机制
            @unlink($attachmentFile);
        }

        // 同步删除OSS文件
        // 本地调试模式不开启
        // $this->delOssFile($path);
    }

    /**
     * 删除OSS文件
     * @param  string $path ''
     * @return ''
     */
    protected function delOssFile($path = '')
    {
        $ftpcfg = get_addon_config('ftp');
        if ($ftpcfg['ftp_usernmae'] && $ftpcfg['ftp_password']) {
            $FTP = new \addons\ftp\library\Auth($ftpcfg['ftp_host'], $ftpcfg['ftp_port'], $ftpcfg['ftp_usernmae'], $ftpcfg['ftp_password'], $ftpcfg['ftp_ssh'], $ftpcfg['ftp_pasv']);
            $FTP->del_file(str_replace('/', DIRECTORY_SEPARATOR, $path));
            $FTP->close();
        }
    }
}
